package lv.solcraft.replication.client;

import java.text.ParseException;

import lv.solcraft.replication.client.boot.ClientBootConfig;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;

public class ClientScheduler implements ApplicationContextAware, InitializingBean, DisposableBean {

    private String cron;
    private Scheduler scheduler;
    private ApplicationContext context;
    private ClientBootConfig config;

    public void setConfig(ClientBootConfig config) {
        this.config = config;
    }

    public void setCron(String cron) {
        this.cron = cron;
    }

    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.context = context;
    }

    public void afterPropertiesSet() throws Exception {
        scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.start();
        schedule("send", new JobDetail(config.getClientName() + "_send", "replication", ReplicationSendJob.class));
        schedule("execute", new JobDetail(
                config.getClientName() + "_execute",
                "replication",
                ReplicationExecuteJob.class));
    }

    private void schedule(String name, JobDetail jobDetail) throws ParseException, SchedulerException {
        Assert.notNull(context, "Application context is null");
        jobDetail.getJobDataMap().put("context", context);
        CronTrigger trigger = new CronTrigger(config.getClientName() + "_Trigger_" + name, "replication");
        trigger.setCronExpression(cron);
        scheduler.scheduleJob(jobDetail, trigger);
    }

    public void destroy() throws Exception {
        if (scheduler != null)
            scheduler.shutdown();
    }
}
